package com.demo.dao;

import com.demo.dao.mapper.SearchOfferMapper;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SpecifyOfferDao  extends BaseDao{
    private static final String ENVIRONMENT_HOMER = "HOMER";

    public OfferDetail selectOrbpOffer(String campaign_subtype) {
        OfferDetail offerDetail = new OfferDetail();
        List<OfferDetail> offerDetailList = new ArrayList<>();
        String offerId = null;

        try (SqlSession session = openSession(ENVIRONMENT_HOMER)){
            SearchOfferMapper mapper = session.getMapper(SearchOfferMapper.class);
            offerId = getSuitableOfferId(mapper.selectMaxScoringOfferId());
            // 查询一批scoring offer
            String idCard = projectSettings.getProperty("idCardTail");
            offerDetailList = mapper.selectOrbpOffer(offerId, campaign_subtype, projectSettings.getProperty("environment"), idCard);
            Collections.shuffle(offerDetailList);
            // 判断当前scoring offer有没有被使用，生成p-offer
            for (int i = 0, length = offerDetailList.size(); i < length; i++) {
                boolean isGenerate = isGeneratePOffer(offerDetailList.get(i).getPersonId());
                SmsCodeDao smsCodeDao = new SmsCodeDao();
                boolean isBlock = smsCodeDao.isBlockSendSmsCode(offerDetailList.get(i).getPersonId());

                // 如果没有生成p-offer，则跳出循环
                if (!isGenerate&&!isBlock) {
                    offerDetail = offerDetailList.get(i);
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return offerDetail;
    }

    protected String getSuitableOfferId(String maxOfferId) {
        StringBuffer offerId = new StringBuffer();
        if (maxOfferId.length() > 7) {
            offerId = offerId.append(maxOfferId.substring(0, maxOfferId.length() - 7)).append("0000000");
        }
        return offerId.toString();
    }

    //查询经过orbp是否生成P-offer
    public Boolean isGeneratePOffer(String personId) {
        boolean isGenerate = false;
        List<String> offerList = new ArrayList<String>();

        try (SqlSession session = openSession(ENVIRONMENT_HOMER)){
            SearchOfferMapper mapper = session.getMapper(SearchOfferMapper.class);
            offerList = mapper.selectOrbp2Poffer(personId);
            if (offerList.size() > 0) {
                isGenerate = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isGenerate;
    }
}
